package com.axin.web.resolver;

import com.axin.blog.api.domain.WebUser;
import com.axin.web.annotation.CurrentUser;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@CurrentUser注解的方法参数，注入当前登录用户   解析器
 * @author lixin
 * @date 2021-07-01 16:15
 */
public class CurrentUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {


	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType().isAssignableFrom(WebUser.class) && parameter.hasParameterAnnotation(CurrentUser.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
								  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
		//获取用户ID
		Object user = request.getAttribute("user", RequestAttributes.SCOPE_REQUEST);
		if (user == null) {
			return null;
		}

		return user;

	}
}
